package com.ape.mapsa.common;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.persistence.PostLoad;

import org.apache.log4j.Logger;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.MenuModel;

import com.ape.mapsa.common.constants.TipoMaterial;
import com.ape.mapsa.produccion.model.Formula;
import com.ape.mapsa.produccion.model.ProdOperator;
import com.ape.mapsa.produccion.service.IProduccionService;

@ManagedBean(name = "operatorsMB")
@ViewScoped
public class OperatorsBean extends BeanCRUD implements Serializable {

	private static final long serialVersionUID = -1865358477053230245L;

	private static final Logger log = Logger.getLogger(OperatorsBean.class);

	@ManagedProperty(value = "#{produccionService}")
	private IProduccionService prodService;

	@ManagedProperty(value = "#{userMB}")
	private UserBean userBean;

	@ManagedProperty(value = "#{colorsMB}")
	private ColorsBean colorsBean;
	@ManagedProperty(value = "#{muestrasMB}")
	private MuestrasBean muestrasBean;

	private List<ProdOperator> operators;
	private List<ProdOperator> operatorsFiltrados = new ArrayList<ProdOperator>();
	private ProdOperator selectedOperator = null;
	private boolean rowSelected = false;

	private boolean showAbm = false;

	private ProdOperator newOperator;

	private TipoMaterial[] tiposMaterial;
	private TipoMaterial tipoMaterialSeleccionado;

	private ProdOperator result;

	private boolean newOperatorDuplicado;

	private String optionPesoEspesor = "";
	private boolean editing = false;

	private String title;

	private Long selectedId;

	@PostConstruct
	public void initialize() {
		log.info("Initializing ITEMS BEAN");
		newOperator = new ProdOperator();
		operators = new ArrayList<ProdOperator>();
		setOperators(prodService.getAllOperators());
		operatorsFiltrados.addAll(operators);
	}

	public void editarOperator(ActionEvent actionEvent) {
		log.info("Editando ProdOperator " + selectedOperator);
		newOperator = selectedOperator;
		if (newOperator != null) {
			editing = true;
		}
	}

	public void saveOperator(ActionEvent actionEvent) {

		FacesContext context = FacesContext.getCurrentInstance();
		log.info("Updating: " + newOperator);
		try {
			prodService.updateOperator(newOperator);
			resetOperator();
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, newOperator.getFirstname(), "Fue guardado satisfactoriamente");
			context.addMessage(null, msg);
		} catch (Exception ex) {
			ex.printStackTrace();
			FacesMessage exceptionEnGuardar = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "El operador no pudo ser guardado.");
			context.addMessage(null, exceptionEnGuardar);
		}
		newOperator = new ProdOperator();
		editing = false;
	}

	public void resetOperator() {
		log.info("Reseting item data");
		newOperator = new ProdOperator();
		editing = false;
		showAbm = false;
	}

	public void rowSelected(SelectEvent event) {
		log.debug("rowSelected" + selectedOperator);
		setRowSelected(selectedOperator != null);
		result = selectedOperator;
	}

	public void getOperator(ActionEvent actionEvent) {
		result = selectedOperator;
	}

	@PostLoad
	public void postload() {
		log.info("ITEMS BEAN BEAN LOADED");
	}

	public void addNewOperator(ActionEvent actionEvent) {
		newOperator.setState(1);
		saveOperator();
	}

	public void addOperator() {
		log.debug("listening add item");
		newOperator.setState(1);
		saveOperator();
	}

	private void saveOperator() {
		FacesContext context = FacesContext.getCurrentInstance();
		log.debug("Saving ProdOperator");
		// Set item code if new

		try {
			prodService.saveOperator(newOperator);
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, newOperator.getFirstname(), "Fue guardado satisfactoriamente");
			context.addMessage(null, msg);
			operatorsFiltrados.add(newOperator);
			operators.add(newOperator);
			showAbm = false;
		} catch (Exception ex) {
			ex.printStackTrace();
			FacesMessage exceptionEnGuardar = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "El operador no pudo ser guardado.");
			context.addMessage(null, exceptionEnGuardar);
		}
	}

	@PreDestroy
	public void predestroy() {
		log.info("ITEMS BEAN BEAN IS GOING TO BE DESTROYED");
	}

	public ProdOperator getSelectedOperator() {
		return selectedOperator;
	}

	public void setSelectedOperator(ProdOperator selectedOperator) {
		this.selectedOperator = selectedOperator;
	}

	public List<ProdOperator> getOperatorsFiltrados() {
		return operatorsFiltrados;
	}

	public void setOperatorsFiltrados(List<ProdOperator> operatorsFiltrados) {
		this.operatorsFiltrados = operatorsFiltrados;
	}

	public boolean isRowSelected() {
		return rowSelected;
	}

	public void setRowSelected(boolean rowSelected) {
		this.rowSelected = rowSelected;
	}

	public ProdOperator getResult() {
		return result;
	}

	public void setResult(ProdOperator result) {
		this.result = result;
	}

	public ProdOperator getNewOperator() {
		return newOperator;
	}

	public void setNewOperator(ProdOperator newOperator) {
		this.newOperator = newOperator;
	}

	public TipoMaterial[] getTiposMaterial() {
		return tiposMaterial;
	}

	public void setTiposMaterial(TipoMaterial[] tiposMaterial) {
		this.tiposMaterial = tiposMaterial;
	}

	public TipoMaterial getTipoMaterialSeleccionado() {
		return tipoMaterialSeleccionado;
	}

	public void setTipoMaterialSeleccionado(TipoMaterial tipoMaterialSeleccionado) {
		this.tipoMaterialSeleccionado = tipoMaterialSeleccionado;
	}

	public ColorsBean getColorsBean() {
		return colorsBean;
	}

	public void setColorsBean(ColorsBean colorsBean) {
		this.colorsBean = colorsBean;
	}

	public IProduccionService getProdService() {
		return prodService;
	}

	public void setProdService(IProduccionService prodService) {
		this.prodService = prodService;
	}

	public List<ProdOperator> getOperators() {
		return operators;
	}

	public void setOperators(List<ProdOperator> operators) {
		this.operators = operators;
	}

	public MuestrasBean getMuestrasBean() {
		return muestrasBean;
	}

	public void setMuestrasBean(MuestrasBean muestrasBean) {
		this.muestrasBean = muestrasBean;
	}

	public boolean isNewOperatorDuplicado() {
		return newOperatorDuplicado;
	}

	public void setNewOperatorDuplicado(boolean newOperatorDuplicado) {
		this.newOperatorDuplicado = newOperatorDuplicado;
	}

	public boolean isEditing() {
		return editing;
	}

	public void setEditing(boolean editing) {
		this.editing = editing;
	}

	public String getOptionPesoEspesor() {
		return optionPesoEspesor;
	}

	public void setOptionPesoEspesor(String optionPesoEspesor) {
		this.optionPesoEspesor = optionPesoEspesor;
	}

	@Override
	public void save(ActionEvent event) {
		saveOperator(event);
		RequestContext.getCurrentInstance().update("addOperatorForm:abm_id");
		RequestContext.getCurrentInstance().update("addOperatorForm:operators:operators");
	}

	@Override
	public void update(ActionEvent event) {
	}

	@Override
	public void create(ActionEvent event) {
		log.info("Articulo nuevo");
		newOperator = new ProdOperator();
		log.debug("item reseted: " + newOperator);
		showAbm = true;
		editing = false;
		RequestContext.getCurrentInstance().update("addOperatorForm:abm_id");
	}

	@Override
	public void edit(ActionEvent event) {
		if (selectedOperator != null && selectedOperator.getId() != null) {
			log.info("Editando ProdOperator " + selectedOperator);
			newOperator = selectedOperator;
			showAbm = true;
			selectedId = selectedOperator.getId();
			if (newOperator != null) {
				editing = true;
			}
			RequestContext.getCurrentInstance().update("addOperatorForm:abm_id");
			RequestContext.getCurrentInstance().scrollTo("addOperatorForm:abm_id");
		} else {
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Desactivación",
					"Debe seleccionar una formula para realizar esta operación");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}
	}

	@Override
	public void delete(ActionEvent event) {
		// TODO Auto-generated method stub
	}

	@Override
	public MenuModel getMenuModel() {
		return menuModel;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public boolean isShowAbm() {
		return showAbm;
	}

	public void setShowAbm(boolean showAbm) {
		this.showAbm = showAbm;
	}

	public UserBean getUserBean() {
		return userBean;
	}

	public void setUserBean(UserBean userBean) {
		this.userBean = userBean;
	}

}
